import React, { useState } from 'react'
import { Card, Table, Tag, Button, Modal, Form, Input, Select, InputNumber, Switch, Space, Alert, Timeline } from 'antd'
import { ExclamationTriangleOutlined, BellOutlined, SettingOutlined, EyeOutlined } from '@ant-design/icons'
import Layout from '../components/Layout/Layout'

const { Option } = Select
const { TextArea } = Input

export default function Alerts() {
  const [alerts, setAlerts] = useState([
    {
      id: 1,
      title: 'A区温度异常',
      type: 'temperature',
      level: 'high',
      status: 'active',
      value: 35.5,
      threshold: 30,
      location: 'A区2楼',
      time: '2024-01-15 14:30:00',
      description: '温度超过阈值，可能影响设备运行'
    },
    {
      id: 2,
      title: '停车位不足',
      type: 'parking',
      level: 'medium',
      status: 'acknowledged',
      value: 95,
      threshold: 90,
      location: 'B区停车场',
      time: '2024-01-15 13:45:00',
      description: '停车位使用率过高，建议引导分流'
    }
  ])

  const [rules, setRules] = useState([
    {
      id: 1,
      name: '温度监控',
      type: 'temperature',
      condition: 'greater_than',
      threshold: 30,
      enabled: true,
      actions: ['notification', 'email']
    },
    {
      id: 2,
      name: '停车位监控',
      type: 'parking',
      condition: 'greater_than',
      threshold: 90,
      enabled: true,
      actions: ['notification']
    }
  ])

  const [modalVisible, setModalVisible] = useState(false)
  const [ruleModalVisible, setRuleModalVisible] = useState(false)
  const [selectedAlert, setSelectedAlert] = useState(null)
  const [form] = Form.useForm()

  const levelColors = {
    low: 'blue',
    medium: 'orange',
    high: 'red',
    critical: 'purple'
  }

  const levelNames = {
    low: '低',
    medium: '中',
    high: '高',
    critical: '严重'
  }

  const statusColors = {
    active: 'red',
    acknowledged: 'orange',
    resolved: 'green'
  }

  const statusNames = {
    active: '活跃',
    acknowledged: '已确认',
    resolved: '已解决'
  }

  const alertColumns = [
    { title: '告警标题', dataIndex: 'title', key: 'title' },
    { 
      title: '级别', 
      dataIndex: 'level', 
      key: 'level',
      render: (level) => (
        <Tag color={levelColors[level]}>{levelNames[level]}</Tag>
      )
    },
    { 
      title: '状态', 
      dataIndex: 'status', 
      key: 'status',
      render: (status) => (
        <Tag color={statusColors[status]}>{statusNames[status]}</Tag>
      )
    },
    { title: '位置', dataIndex: 'location', key: 'location' },
    { title: '时间', dataIndex: 'time', key: 'time' },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button 
            size="small" 
            icon={<EyeOutlined />}
            onClick={() => {
              setSelectedAlert(record)
              setModalVisible(true)
            }}
          >
            详情
          </Button>
          {record.status === 'active' && (
            <Button size="small" type="primary">
              确认
            </Button>
          )}
        </Space>
      )
    }
  ]

  const ruleColumns = [
    { title: '规则名称', dataIndex: 'name', key: 'name' },
    { title: '监控类型', dataIndex: 'type', key: 'type' },
    { title: '条件', dataIndex: 'condition', key: 'condition' },
    { title: '阈值', dataIndex: 'threshold', key: 'threshold' },
    { 
      title: '状态', 
      dataIndex: 'enabled', 
      key: 'enabled',
      render: (enabled) => (
        <Tag color={enabled ? 'green' : 'red'}>
          {enabled ? '启用' : '禁用'}
        </Tag>
      )
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button size="small">编辑</Button>
          <Button size="small" danger>删除</Button>
        </Space>
      )
    }
  ]

  const handleAcknowledge = (id) => {
    setAlerts(prev =>
      prev.map(alert =>
        alert.id === id ? { ...alert, status: 'acknowledged' } : alert
      )
    )
  }

  const handleResolve = (id) => {
    setAlerts(prev =>
      prev.map(alert =>
        alert.id === id ? { ...alert, status: 'resolved' } : alert
      )
    )
  }

  return (
    <Layout>
      <div style={{ padding: '24px' }}>
        <Card 
          title="智能预警系统"
          tabList={[
            { key: 'alerts', tab: '告警列表' },
            { key: 'rules', tab: '预警规则' },
            { key: 'analytics', tab: '告警分析' }
          ]}
          activeTabKey="alerts"
          extra={
            <Button 
              type="primary" 
              icon={<SettingOutlined />}
              onClick={() => setRuleModalVisible(true)}
            >
              新建规则
            </Button>
          }
        >
          <Alert
            message="系统状态"
            description={`当前有 ${alerts.filter(a => a.status === 'active').length} 个活跃告警，${alerts.filter(a => a.status === 'acknowledged').length} 个已确认告警。`}
            type="info"
            showIcon
            style={{ marginBottom: 16 }}
          />

          <Table
            columns={alertColumns}
            dataSource={alerts}
            rowKey="id"
            pagination={{ pageSize: 10 }}
          />
        </Card>

        {/* 告警详情模态框 */}
        <Modal
          title="告警详情"
          open={modalVisible}
          onCancel={() => setModalVisible(false)}
          footer={[
            <Button key="close" onClick={() => setModalVisible(false)}>
              关闭
            </Button>,
            selectedAlert?.status === 'active' && (
              <Button 
                key="acknowledge" 
                type="primary"
                onClick={() => {
                  handleAcknowledge(selectedAlert.id)
                  setModalVisible(false)
                }}
              >
                确认告警
              </Button>
            ),
            selectedAlert?.status === 'acknowledged' && (
              <Button 
                key="resolve" 
                type="primary"
                onClick={() => {
                  handleResolve(selectedAlert.id)
                  setModalVisible(false)
                }}
              >
                解决告警
              </Button>
            )
          ]}
        >
          {selectedAlert && (
            <div>
              <Timeline>
                <Timeline.Item color="red">
                  <strong>告警触发</strong>
                  <div>时间: {selectedAlert.time}</div>
                  <div>位置: {selectedAlert.location}</div>
                  <div>当前值: {selectedAlert.value}</div>
                  <div>阈值: {selectedAlert.threshold}</div>
                </Timeline.Item>
                {selectedAlert.status !== 'active' && (
                  <Timeline.Item color="orange">
                    <strong>告警确认</strong>
                    <div>确认时间: 2024-01-15 14:35:00</div>
                    <div>确认人: 张三</div>
                  </Timeline.Item>
                )}
                {selectedAlert.status === 'resolved' && (
                  <Timeline.Item color="green">
                    <strong>告警解决</strong>
                    <div>解决时间: 2024-01-15 15:00:00</div>
                    <div>解决人: 李四</div>
                  </Timeline.Item>
                )}
              </Timeline>
              
              <div style={{ marginTop: 16 }}>
                <strong>描述:</strong>
                <p>{selectedAlert.description}</p>
              </div>
            </div>
          )}
        </Modal>

        {/* 新建规则模态框 */}
        <Modal
          title="新建预警规则"
          open={ruleModalVisible}
          onOk={() => form.submit()}
          onCancel={() => setRuleModalVisible(false)}
        >
          <Form
            form={form}
            layout="vertical"
            onFinish={(values) => {
              const newRule = {
                id: Date.now(),
                ...values,
                enabled: true
              }
              setRules(prev => [...prev, newRule])
              setRuleModalVisible(false)
              form.resetFields()
            }}
          >
            <Form.Item name="name" label="规则名称" rules={[{ required: true }]}>
              <Input placeholder="请输入规则名称" />
            </Form.Item>
            
            <Form.Item name="type" label="监控类型" rules={[{ required: true }]}>
              <Select placeholder="选择监控类型">
                <Option value="temperature">温度</Option>
                <Option value="humidity">湿度</Option>
                <Option value="parking">停车位</Option>
                <Option value="energy">能耗</Option>
                <Option value="security">安全</Option>
              </Select>
            </Form.Item>
            
            <Form.Item name="condition" label="条件" rules={[{ required: true }]}>
              <Select placeholder="选择条件">
                <Option value="greater_than">大于</Option>
                <Option value="less_than">小于</Option>
                <Option value="equals">等于</Option>
              </Select>
            </Form.Item>
            
            <Form.Item name="threshold" label="阈值" rules={[{ required: true }]}>
              <InputNumber style={{ width: '100%' }} placeholder="请输入阈值" />
            </Form.Item>
            
            <Form.Item name="actions" label="告警动作" rules={[{ required: true }]}>
              <Select mode="multiple" placeholder="选择告警动作">
                <Option value="notification">系统通知</Option>
                <Option value="email">邮件通知</Option>
                <Option value="sms">短信通知</Option>
                <Option value="webhook">Webhook</Option>
              </Select>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </Layout>
  )
}
